<template>
  <div class="admin-header">
    <!-- 其他内容 -->
    <div class="user-area">
      <el-button type="primary" link :loading="checkingUpdate" @click="checkUpdate">
        <el-icon><Refresh /></el-icon>
        检查更新
      </el-button>
      <el-button type="danger" link @click="handleLogout">
        <el-icon><SwitchButton /></el-icon>
        退出登录
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, SwitchButton } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()
const checkingUpdate = ref(false)

// 检查更新
const checkUpdate = async () => {
  if (checkingUpdate.value) return

  try {
    checkingUpdate.value = true
    const res = await request.get('/api/system/check-update')

    if (res.hasUpdate) {
      const action = await ElMessageBox.confirm(
        `发现新版本 ${res.latestVersion}\n\n${res.description || ''}`,
        '更新提示',
        {
          confirmButtonText: '立即更新',
          cancelButtonText: '暂不更新',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
      )

      if (action === 'confirm') {
        // 打开下载链接
        window.open(res.downloadUrl, '_blank')
      }
    } else {
      ElMessage.success('当前已是最新版本')
    }
  } catch (error) {
    ElMessage.error(error.message || '检查更新失败')
  } finally {
    checkingUpdate.value = false
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout()
    router.push('/login')
  })
}
</script>

<style lang="scss" scoped>
.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.user-area {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-area .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
